window.onload = initAll;
var usedNum = new Array(76);

function initAll() {
	if (document.getElementById) {
		document.getElementById("reload").onclick = anotherCard;
		newCard();
	} else {
		alert("Sorry, your browser doesn't support this script.\nPlease update your browser.");
	}
}

function anotherCard() {
	for (var i = 0; i < usedNum.length; ++i) {
		usedNum[i] = false;
	}

	newCard();
	return false;
}

function newCard() {
	for (var i = 0; i < 24; ++i) {
		setSquare(i);
	}
}

function setSquare(squareID) {
	var div = Math.floor(squareID / 5);
	var colBasic = div * 15;
	var currentSquare = "square" + squareID;
	var randNum;

	do {
		randNum = colBasic + getRandomNum();
	} while (usedNum[randNum]);
	
	usedNum[randNum] = true;
	document.getElementById(currentSquare).innerHTML = randNum;
	document.getElementById(currentSquare).className = "";
	document.getElementById(currentSquare).onclick = toggleColor;	
}

function getRandomNum() {
	return Math.floor(Math.random() * 15 + 1);
}

function toggleColor(evt) {
	// if (IE)
	var thisSquare = (evt) ? evt.target : window.event.srcElement;
	thisSquare.className = (thisSquare.className == "") ? "pickedBG" : "";
	checkWin();
}

function checkWin() {
	var winningOption = -1;
	var setSquares = 0;
	var winners = new Array(31, 992, 15360, 507904, 557328, 1083458, 2162820, 4329736, 8519745, 16252928);

	for (var i = 0; i < 24; ++i) {
		var square = getElementById("square" + i);
		if (square.className != "") {
			square.className = "pickedBG";
			setSquares = setSquares | Math.pow(2, i);
		}
	}

	for (var i = 0; i < winners.length; ++i) {
		if ((winners[i] & setSquares) == winners[i]) {
			winningOption = i;
		}
	}

	if (winningOption > -1) {
		for (var i = 0; i < 24; ++i) {
			if (winners[winningOption] & Math.pow(2, i)) {
				currentSquare = "square" + i;
				document.getElementById(currentSquare).className = "winningBG";
			}
		}
	}
}